//
//  ViewController.m
//  CTCollectionViewDemo
//
//  Created by Andney Jack on 2021/6/3.
//

#import "ViewController.h"
#import <CTCollectionViewColumnLayout/CTCollectionViewColumnLayout.h>

static inline UIColor * RandomColor(void)
{
    return [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1];
}

@interface ViewController () <UICollectionViewDataSource, CTCollectionViewDelegateColumnLayout>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet CTCollectionViewColumnLayout *flowLayout;
@property (nonatomic, strong) NSMutableArray<NSMutableArray<NSNumber *> *> *dataList;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.dataList = [[NSMutableArray alloc] initWithCapacity:0];

    self.flowLayout.allowUseSafeAreaInsets = NO;
    self.flowLayout.itemRenderDirection = CTCollectionViewItemRenderDirectionRightToLeft;

    self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CTCollectionElementKindSectionHeader withReuseIdentifier:@"section_header"];

    [self reloadData];
}

- (void)reloadData {
    [self.dataList removeAllObjects];

    for (NSInteger section = 0; section < 4; section++) {
        NSMutableArray *cellHeights = [[NSMutableArray alloc] initWithCapacity:0];
        NSInteger cellCount = MAX(arc4random() % 20, 1);

        for (NSInteger item = 0; item < cellCount; item++) {
            [cellHeights addObject:@(80 + arc4random() % 200)];
        }
        [self.dataList addObject:cellHeights];
    }

    [self.collectionView reloadData];
}

#pragma mark - UICollectionView DataSource & Delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataList.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataList[section].count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.contentView.backgroundColor = RandomColor();
    UILabel *textLabel = [cell.contentView viewWithTag:1];
    if (!textLabel) {
        textLabel = [UILabel new];
        textLabel.tag = 1;
        textLabel.font = [UIFont systemFontOfSize:15];
        textLabel.textColor = [UIColor whiteColor];
        textLabel.textAlignment = NSTextAlignmentCenter;
        textLabel.numberOfLines = 2;
        [cell.contentView addSubview:textLabel];

        textLabel.translatesAutoresizingMaskIntoConstraints = NO;
        [textLabel.centerXAnchor constraintEqualToAnchor:cell.contentView.centerXAnchor].active = YES;
        [textLabel.centerYAnchor constraintEqualToAnchor:cell.contentView.centerYAnchor].active = YES;
    }

    textLabel.text = [NSString stringWithFormat:@"section: %ld\nitem: %ld", indexPath.section + 1, indexPath.item + 1];

    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:CTCollectionElementKindSectionHeader]) {
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"section_header" forIndexPath:indexPath];

        UILabel *titleLabel = [headerView viewWithTag:1];
        if (!titleLabel) {
            headerView.backgroundColor = RandomColor();

            UILabel *titleLabel = [[UILabel alloc] init];
            titleLabel.tag = 1;
            titleLabel.font = [UIFont systemFontOfSize:20];
            titleLabel.textColor = [UIColor darkTextColor];
            [headerView addSubview:titleLabel];

            titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
            [NSLayoutConstraint constraintWithItem:titleLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:headerView attribute:NSLayoutAttributeCenterY multiplier:1 constant:0].active = YES;
            [NSLayoutConstraint constraintWithItem:titleLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:headerView attribute:NSLayoutAttributeLeftMargin multiplier:1 constant:20].active = YES;
        }

        titleLabel.text = [NSString stringWithFormat:@"区头：%ld", indexPath.section + 1];
        return headerView;
    }

    return nil;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView layout:(CTCollectionViewColumnLayout *)layout columnCountForSection:(NSInteger)section {
    return section % 2 ? 2 : 3;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(CTCollectionViewColumnLayout *)layout sizeForItemAtIndexPath:(NSIndexPath *)indexPath columnWidth:(CGFloat)columnWidth
{
    return CGSizeMake(columnWidth, self.dataList[indexPath.section][indexPath.item].floatValue);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(CTCollectionViewColumnLayout *)layout heightForHeaderInSection:(NSInteger)section {
    return section > 0 ? 50 : 0;
}

- (CTCollectionViewItemRenderDirection)collectionView:(UICollectionView *)collectionView layout:(CTCollectionViewColumnLayout *)layout itemRenderDirectionForSectionAtIndex:(NSInteger)section {
    if (section % 2) {
        return CTCollectionViewItemRenderDirectionColumnFirst;
    } else {
        return CTCollectionViewItemRenderDirectionShortestFirst;
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView layout:(CTCollectionViewColumnLayout *)layout shouldPinToVisibleBoundsForSupplementaryViewOfKind:(NSString *)kind atSection:(NSInteger)section
{
    if (section >= 1) {
        return YES;
    }
    return NO;
}

- (IBAction)buttonClick:(UIButton *)sender {
    if ([sender.currentTitle isEqualToString:@"跳转"]) {
        NSInteger section = arc4random() % [self.collectionView numberOfSections];
        NSInteger item = arc4random() % [self.collectionView numberOfItemsInSection:section];

        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:section] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES];
    } else if ([sender.currentTitle isEqualToString:@"刷新"]) {
        [self reloadData];
    }
}

@end
